# -*- coding: utf-8 -*-
from django.core.context_processors import csrf
from django.shortcuts import render_to_response,redirect,get_object_or_404
from forms import *
import hashlib
from django.contrib.auth.decorators import login_required

@login_required
def create(request,id=0):
    if request.POST:
        form = CreateFileForm(data=request.POST,files=request.FILES,initial = {'parent':id})
        if form.is_valid():
            f=form.save()
            if f==None:
                context={}
                context['form']=form
                return render_to_response('vfile/create.html',context) 
            return redirect('/vdir/detail/'+str(f.dir.id))
        context={}
        context['form']=form
        context.update(csrf(request))
        return render_to_response('vfile/create.html',context) 
    if id>0:
        form = CreateFileForm(initial = {'parent':id})
    else:
        form = CreateFileForm(initial = {'parent':VDir.objects.all()[0].id})
    
    context={'form':form}
    context.update(csrf(request))
    return render_to_response('vfile/create.html',context)

@login_required
def delete(request,id):
    vf = get_object_or_404(VFile,pk=id)

    from django.conf import settings

    realpath = settings.MEDIA_ROOT+vf.dir.get_full_path()+vf.name
    import os
    if os.path.exists(realpath):
        os.remove(realpath) 

    vf.delete()
    return redirect('/vdir/detail/'+str(vf.dir.id))
